package com.oceansoft.mobile.oauth.service;

import com.oceansoft.mobile.common.util.CacheBaseService;
import com.oceansoft.mobile.oauth.jdbc.SecurityRepository;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Created by BEN on 2016/5/1.
 */
@Component
public class SecurityServiceImpl implements ISecurityService{


    @Resource
    private SecurityRepository repository;


    public boolean validateToken(String access_token) {
        boolean flag = Boolean.FALSE;

        OAuth2AccessToken OAuth2AccessToken = repository.getAccessToken(access_token);

        if (OAuth2AccessToken != null) {
            flag = !OAuth2AccessToken.isExpired();
        }

        return flag;
    }

    @Override
    public boolean validateAndCache(String access_token,String sessionid) {
        boolean flag = Boolean.FALSE;
        OAuth2AccessToken OAuth2AccessToken = repository.getAccessToken(access_token);

        if (OAuth2AccessToken != null) {
            flag = !OAuth2AccessToken.isExpired();
        }

        if(flag){
            String cachekey = "OAUTHTOKEN:"+sessionid;
            if (!CacheBaseService.getInstance().exists(cachekey)) {
                CacheBaseService.getInstance().cache(cachekey,access_token,OAuth2AccessToken.getExpiresIn());
            }
        }

        return flag;
    }

}
